<?php

/**
 * This is the model class for table "tbl_jobs".
 *
 * The followings are the available columns in table 'tbl_jobs':
 * @property string $jobid
 * @property string $custno
 * @property string $locno
 * @property string $billloc
 * @property string $supervisor
 * @property string $start
 * @property string $projend
 * @property string $post
 * @property string $jobstatus
 * @property string $billingstatus
 * @property string $actualend
 * @property string $jobsalesperson
 * @property string $department
 * @property string $description
 * @property string $customerpo
 * @property string $closedate
 * @property string $installcrew
 * @property string $addeddate
 */
class Jobs extends CActiveRecord
{
    const STATUS_OPEN=1;
    const STATUS_PENDING_WANTDATE=2;
    const STATUS_PENDING_REVIEW=3;
    const STATUS_PENDING_90DAYREVIEW=4;
    const STATUS_PENDING_60DAYREVIEW=5;
    const STATUS_PENDING_30DAYREVIEW=6;
    const STATUS_PENDING_15DAYREVIEW=7;
    const STATUS_PENDING_PULLPARTS=8;
    const STATUS_PENDING_CREATEINSTALLPACKET=9;
    const STATUS_PENDING_DELIVERYANDINSTALL=10;
    const STATUS_INSTALL=11;
    const STATUS_CORRECTIVEACTIONS=13;
    const STATUS_INSTALLCOMPLETE=14;
    const STATUS_COMPLETE=15;
    
    const BILL_QUOTE_PENDING=1;
    const BILL_SALESORDER=2;
    const BILL_PENDING_SOACK=3;
    const BILL_SOACK_50REQUESTED=4;
    const BILL_DEPOSIT_RECEIVED=5;
    const BILL_PENDING_INVOICE=6;
    const BILL_PENDING_PAYMENT=7;
    const BILL_COMPLETE_PAID=8;
    /**
     * Returns the static model of the specified AR class.
     * @return Jobs the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'tbl_jobs';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('custno, locno,jobstatus', 'required'),
            array('jobclass', 'numerical', 'integerOnly' => true),
            array('jobid', 'length', 'max' => 41),
            array('custno', 'length', 'max' => 7),
            array('locno, billloc', 'length', 'max' => 5),
            array('supervisor, jobsalesperson, department, installcrew', 'length', 'max' => 4),
            array('post', 'length', 'max' => 1),
            array('jobstatus, billingstatus', 'length', 'max' => 10),
            array('customerpo', 'length', 'max' => 40),
            array('start, projend, actualend, closedate', 'safe'),
            array('description', 'length', 'max' => 99999999),
          
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('jobid, custno, locno, billloc, supervisor, start, projend, post, jobstatus, billingstatus, actualend, jobsalesperson, department, description, customerpo, closedate, installcrew', 'safe', 'on' => 'search'),
        );
    }
  
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'customer'=>array(self::BELONGS_TO,'Customers','custno'),
            'jobclassModel' => array(self::BELONGS_TO, 'Jobclass', 'jobclass'),
            'salesOrderList'=>array(self::HAS_MANY,'Invoice','jobnumber','condition'=>'invoicetype=:type','params'=>array('type'=>Invoice::TYPE_SALES_ORDERS)),
            'salesOrderCount'=>array(self::STAT,'Invoice','jobnumber','condition'=>'invoicetype=:type','params'=>array('type'=>Invoice::TYPE_SALES_ORDERS)),
            'quoteList'=>array(self::HAS_MANY,'Invoice','jobnumber','condition'=>'invoicetype=:type','params'=>array('type'=>Invoice::TYPE_QUOTE)),
            'quoteCount'=>array(self::STAT,'Invoice','jobnumber','condition'=>'invoicetype=:type','params'=>array('type'=>Invoice::TYPE_QUOTE)),
            'invoiceList'=>array(self::HAS_MANY,'Invoice','jobnumber','condition'=>'invoicetype=:type','params'=>array('type'=>Invoice::TYPE_INVOICE)),
            'invoiceAndCMList'=>array(self::HAS_MANY,'Invoice','jobnumber','condition'=>'invoicetype=:itype or invoicetype=:cmtype',
                'params'=>array('itype'=>Invoice::TYPE_INVOICE,'cmtype'=>  Invoice::TYPE_CREDIT_MEMO)),
           
            //,'condition'=>'custno=:custno AND locno=:locno','params'=>array('custno' => $this->custno,'locno' => $this->locno)
        );
    }
    public function getLocation(){
        return Locations::model()->find('custno=:custno and locno=:locno',array(
            'custno'=>$this->custno,
            'locno'=>$this->locno
        ));
    }
    public function getBillLocation()
    {
        return $location = Locations::model()->find('id=:id', array(
            'id' => $this->billloc
        ));
    }


    public function beforeDelete()
    {
        Yii::app()->db->createCommand('delete from tbl_jobs_notes where jobid=:id')->bindValue('id', $this->jobid)->query();
        Yii::app()->db->createCommand('delete from tbl_jobs_documents where jobid=:id')->bindValue('id', $this->jobid)->query();
        return parent::beforeDelete();
    }

    public function getBillToList()
    {
        $list = Locations::model()->findAll('locationinactive=0 AND custno=:custno', array('custno' => $this->custno));
        $customer = $this->customer;
        $rs = array(
            //'-1'=>$this->custno.' - '.$customer->lastname.' | '.$customer->add1.' | '.$customer->city.' | '.$customer->state;
            '-1' => 'Parent Company'
        );
        if (count($list) > 0) {
            foreach ($list as $item) {
                $rs[$item->id] = $item->locno . ' - ' . $item->locname . ' | ' . $item->add1 . ' | ' . $item->city . ' | ' . $item->state;
            }
        }
        return $rs;
    }

    public function init()
    {
        parent::init();
        $this->jobid = DateUtil::getDefaultYear() . '-' . Counters::model()->getNextNumber(DateUtil::getDefaultYear().'-job');
    }

    public function beforeValidate()
    {


        return parent::beforeValidate();
    }

    public function beforeSave()
    {
        if ($this->isNewRecord) {
            $this->addeddate=DateUtil::getDefaultCurrentDateTime();
            $counter = Counters::model()->getNextNumber(DateUtil::getDefaultYear().'-job') + 1;
            $this->jobid = DateUtil::getDefaultYear() . '-' . $counter;
            $this->setJobAndBillStatus(NULL, self::BILL_QUOTE_PENDING);            
        }               
     
     //   $this->updateSalesOrderStatus();
        
        return parent::beforeSave();
    }

    public function afterSave(){
        if($this->isNewRecord){
            Counters::model()->saveNumber(DateUtil::getDefaultYear().'-job');
        }
        return parent::afterSave();
    }
    
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'jobid' => 'Job Number',
            'custno' => 'Custno',
            'locno' => 'Locno',
            'billloc' => 'Bill To',
            'supervisor' => 'Super Visor',
            'start' => 'Start Date',
            'projend' => 'Want Date',
            'post' => 'Post',
            'jobstatus' => 'Job Status',
            'billingstatus' => 'Billing Status',
            'actualend' => 'Actual End Date',
            'jobsalesperson' => 'Sales Person',
            'department' => 'Department',
            'description' => 'Description',
            'customerpo' => 'Customer PO',
            'closedate' => 'Close Date',
            'installcrew' => 'Install Crew',
            'jobclass' => 'Job Class',
            'addeddate' => 'Create Date'
        );
    }

    public static function getList()
    {
        $list = Jobs::model()->findAll();
        $rs = array();
        if (count($list) > 0) {
            foreach ($list as $item) {
                $rs[$item->jobid] = $item->jobid;
            }
        }
        return $rs;
    }
    public function isWantDateEnabled(){
        if($this->jobstatus==Jobs::STATUS_PENDING_WANTDATE){
            return true;
        }
        return false;
    }
    public static function getJobByLocation($custno, $locno)
    {
        $list = Yii::app()->db->createCommand('select * from tbl_jobs where custno=:custno AND locno=:locno')
            ->bindValues(array(
            'custno' => $custno,
            'locno' => $locno
        ))->queryAll();
        $rs = array(
            NULL=>'N/A'
        );
        foreach ($list as $item) {
            $rs[$item['jobid']] = $item['jobid'] . ' ' . $item['description'];
        }
        return $rs;
    }
    
    public function updateSalesOrderStatus(){
        $rs=Yii::app()->db->createCommand()->update('tbl_invoice',array('salesorderstatus'=>$this->jobstatus),'jobnumber=:id AND invoicetype=:type',
                array(                    
                    'id'=>$this->jobid,
                    'type'=>Invoice::TYPE_SALES_ORDERS
                ));
        if($rs>0)return true;
        return false;
    }
     public function setJobAndBillStatus($status=NULL,$billstatus=NULL){
        if($status!=NULL){
            $this->jobstatus=$status;
        }
        if($billstatus!=NULL){
            $this->billingstatus=$billstatus;
        }
        if($status==self::STATUS_INSTALLCOMPLETE){ //install complete
            $this->billingstatus=self::BILL_PENDING_INVOICE; //pending, invoice
        }
        if($billstatus==self::BILL_COMPLETE_PAID){ //paid in full
            $this->jobstatus=self::STATUS_COMPLETE; //complete
        }
        
        
    }
       public static function getTotalJobs($empno=false){
        if($empno)
            return Yii::app()->db->createCommand('select count(*)
                                                 from tbl_jobs where jobstatus is not null and jobsalesperson=:empno')
                                                ->bindValue('empno', $empno)->queryScalar();
            else
        return Yii::app()->db->createCommand('select count(*) from tbl_jobs where jobstatus is not null')->queryScalar();
    }
    
    

}
